package com.woniu.communitymanagement.interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class AuthInterceptor extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        HandlerInterceptor handlerInterceptor =new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                boolean isGo=false;
                String url=request.getRequestURI();//获取当前请求的数据接口路径
                //获取用户请求时传递的uid
                String uid=request.getParameter("uid");
                //获取根据uid查询redis中是否有对应的数据
                Jedis jedis = new Jedis();
                if(url.contains("/user/login")||url.contains("/user/signIn")){
                    isGo=true;//如果登陆就放行
                }else if(jedis.get(uid+"")!=null){//如果用户uid的值和redis中保存的值一致，则放行
                    isGo=true;
                }
                jedis.close();//释放资源
                System.out.println(url);
                return isGo;
            }

            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
                HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
            }

        };
        registry.addInterceptor(handlerInterceptor).addPathPatterns("/**");
    }
}
